﻿namespace YidanSoft.Library.EditorUtility.WinControls
{
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using YidanSoft.Library.EditorUtility.Win32;

    internal class HeaderHook : NativeWindow
    {
        private ListViewEx listView = null;

        public HeaderHook(ListViewEx lv)
        {
            this.listView = lv;
        }

        protected override void WndProc(ref Message m)
        {
            int num2;
            int msg = m.Msg;
            Point pt = new Point(0, 0);
            switch (msg)
            {
                case 0x201:
                case 0x202:
                    pt = WindowsAPI.GetPointFromLPARAM((int) m.LParam);
                    this.listView.LastMousePosition = pt;
                    break;
            }
            if ((msg == 0x201) && !this.listView.Tracking)
            {
                for (num2 = 0; num2 < this.listView.Columns.Count; num2++)
                {
                    if (this.listView.GetHeaderItemRect(num2).Contains(pt))
                    {
                        this.listView.PressedHeaderItem = num2;
                        WindowsAPI.InvalidateRect(m.HWnd, IntPtr.Zero, 0);
                        break;
                    }
                }
            }
            if ((msg == 0x202) && !this.listView.Tracking)
            {
                this.listView.PressedHeaderItem = -1;
                for (num2 = 0; num2 < this.listView.Columns.Count; num2++)
                {
                    if (this.listView.GetHeaderItemRect(num2).Contains(pt))
                    {
                        this.listView.LastSortedColumn = num2;
                        if (this.listView.Sorting == SortOrder.None)
                        {
                            this.listView.Sorting = SortOrder.Descending;
                        }
                        else if (this.listView.Sorting == SortOrder.Ascending)
                        {
                            this.listView.Sorting = SortOrder.Descending;
                        }
                        else
                        {
                            this.listView.Sorting = SortOrder.Ascending;
                        }
                        break;
                    }
                }
                WindowsAPI.InvalidateRect(m.HWnd, IntPtr.Zero, 0);
            }
            base.WndProc(ref m);
        }
    }
}

